const _ = require("lodash");
const node_xlsx = require("node-xlsx");

/*
 * 构建xlsx内容，opts中每一项为{sheet：String, title: [{name : xxx, key : xxx}], data: [{key: value, key: value, ...}]}
 * @param opts = Array
 * @returns Buffer
 */
function buildExcelResultBuf(opts){
    let finData = [];
    for (let sheet of opts) {
        let data = [];
        let title = sheet.title.map(function (item) {
            return item.name;
        });
        data.push(title);

        for (let key in sheet.data) {
            let row = [];
            _.each(sheet.title, function(item){
                row.push(sheet.data[key][item.key]);
            });
            data.push(row);
        }
        finData.push({name : sheet.sheet, data : data});
    }

    let buffer = node_xlsx.build(finData);
    return buffer;
}

module.exports = {
    buildExcelResultBuf,
}
